package com.xoa.service.party;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.party.EnCommunityVolunteerMapper;
import com.xoa.dao.party.MapOwnerinfoMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.party.EnCommunityVolunteer;
import com.xoa.model.users.Users;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.newwrapper.BaseWrapper;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gsb on 2018/1/10.
 */
@Service
public class EnCommunityVolunteerService {

    @Resource
    private EnCommunityVolunteerMapper enCommunityVolunteerMapper;

    @Resource
    private SysCodeMapper sysCodeMapper;

    @Autowired
    MapOwnerinfoMapper mapOwnerinfoMapper;
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-10 上午10:30:51
     * 类介绍  :   新建
     * 构造参数:
     *
     */
    public ToJson<EnCommunityVolunteer> insertSelective(EnCommunityVolunteer enCommunityVolunteer, HttpServletRequest request){
        ToJson<EnCommunityVolunteer> json = new ToJson<>();
        try {
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            enCommunityVolunteer.setCreateUser(user.getUserId());
            enCommunityVolunteer.setCreateTime(DateFormat.getDatestr(new Date()));
            enCommunityVolunteerMapper.insertSelective(enCommunityVolunteer);
            json.setFlag(0);
            json.setMsg("新建成功");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-10 上午10:36:51
     * 类介绍  :   删除
     * 构造参数:
     *
     */
    public ToJson<EnCommunityVolunteer> deleteByPrimaryKey(Integer vid){
        ToJson<EnCommunityVolunteer> json = new ToJson<>();
        try {
            enCommunityVolunteerMapper.deleteByPrimaryKey(vid);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-10 上午10:46:51
     * 类介绍  :   修改
     * 构造参数:
     *
     */
    public ToJson<EnCommunityVolunteer> updateByPrimaryKeySelective(EnCommunityVolunteer enCommunityVolunteer) {
        ToJson<EnCommunityVolunteer> json = new ToJson<>();
        try {
            enCommunityVolunteerMapper.updateByPrimaryKeySelective(enCommunityVolunteer);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-10 上午10:46:51
     * 类介绍  :   详情
     * 构造参数:
     *
     */
    public ToJson<EnCommunityVolunteer> selectById(Integer vid){
        ToJson<EnCommunityVolunteer> json = new ToJson<>();
        try {
            EnCommunityVolunteer enCommunityVolunteer = enCommunityVolunteerMapper.selectById(vid);
            json.setObject(enCommunityVolunteer);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }
    /**
     *
     * 创建作者:   季佳伟
     * 创建日期:   2018-1-10 上午11:26:51
     * 类介绍  :   列表
     * 构造参数:
     *
     */
    public ToJson<EnCommunityVolunteer> queryList(EnCommunityVolunteer enCommunityVolunteer, Integer page, Integer pageSize,
                                                  boolean useFlag, HttpServletRequest request, HttpServletResponse response, String export) {
        ToJson<EnCommunityVolunteer> json = new ToJson<>();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            if(useFlag){
                map.put("page", pageParams);
            }
            map.put("enCommunityVolunteer",enCommunityVolunteer);
            List<EnCommunityVolunteer> enCommunityVolunteerList = enCommunityVolunteerMapper.selectList(map);
            if (enCommunityVolunteerList!=null && enCommunityVolunteerList.size()>0){
                for (EnCommunityVolunteer enCommunityVolunteer1:enCommunityVolunteerList){
                    if (enCommunityVolunteer1 != null && !StringUtils.checkNull(enCommunityVolunteer1.getGrid())) {
                        SysCode singleCode = sysCodeMapper.getSingleCode("TYPE_OF_ACCOUNT", enCommunityVolunteer1.getGrid());
                        enCommunityVolunteer1.setGrid(singleCode.getCodeName());
                    }
                    if ("1".equals(enCommunityVolunteer1.getSex())){
                        enCommunityVolunteer1.setSex("男");
                    }else if ("0".equals(enCommunityVolunteer1.getSex())){
                        enCommunityVolunteer1.setSex("女");
                    }else {
                        enCommunityVolunteer1.setSex("");
                    }
                }

            }
            json.setObj(enCommunityVolunteerList);
            json.setTotleNum(pageParams.getTotal());
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
    * @Author 程叶同
    * @Description 导出
    * @Date 14:49 2018/3/6
    */
    public BaseWrapper outPutFile(HttpServletRequest request, HttpServletResponse response){
        BaseWrapper baseWrapper=new BaseWrapper();
        Map<String,Object> map=new HashMap<String,Object>();
        List<EnCommunityVolunteer> enCommunityVolunteerList = enCommunityVolunteerMapper.selectList(map);
        if(enCommunityVolunteerList!=null){
            for(EnCommunityVolunteer en: enCommunityVolunteerList){
                if ("1".equals(en.getSex())){
                    en.setSex("男");
                }else if ("0".equals(en.getSex())){
                    en.setSex("女");
                }else {
                    en.setSex("");
                }
            }
        }
        /*if(ids!=null&&ids!=""){
            String[] id=ids.split(",");
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("id",id);
            illegalrentgroups=illegalrentgroupMapper.selectList(map);
        }*/

        try {

            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("社区志愿者管理表", 9);
            String[] secondTitles = {"服务社区","姓名","性别","年龄","政治面貌","身份证号","居住地址","加入志愿者时间"};
            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

            // String[] beanProperty = {user.getDep().getDeptName(),"userName","userPrivName", "roleAuxiliaryName","online","sex","online","telNoDept","telNoDept","departmentPhone","email"};
            String[] beanProperty = {"gridName","name","sex","age","politicalFace","idNum",
                    "address","joinTime"};

            HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, enCommunityVolunteerList, beanProperty);
            ServletOutputStream out = response.getOutputStream();

            String filename = "社区志愿者管理表.xls";
            filename = FileUtils.encodeDownloadFilename(filename,
                    request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition",
                    "attachment;filename=" + filename);
            workbook.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return  baseWrapper;
    }
    public BaseWrapper inPutFile(MultipartFile file){
        int count=0;//計數器
        BaseWrapper baseWrapper=new BaseWrapper();
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (file.isEmpty()) {
                baseWrapper.setMsg("请上传文件！");
                baseWrapper.setFlag("false");
                return baseWrapper;
            }else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");//判读当前系统
                    //读取配置文件
                    ResourceBundle rb = ResourceBundle.getBundle("upload");
                    String osName = System.getProperty("os.name");
                    StringBuffer path = new StringBuffer();
                    if (osName.toLowerCase().startsWith("win")) {
                        path = path.append(rb.getString("upload.win"));
                    } else {
                        path = path.append(rb.getString("upload.linux"));
                    }
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
//                    // 将文件上传成功后进行读取文件
//                    // 进行读取的路径
//                    String readPath = path.append(newFileName).toString();
//                    InputStream in = new FileInputStream(readPath);
                    InputStream in =  file.getInputStream();

                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    EnCommunityVolunteer enCommunityVolunteer = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        enCommunityVolunteer = new EnCommunityVolunteer();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //服务社区
                                            SysCode sysCode=new SysCode();
                                            sysCode.setCodeName(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            sysCode.setParentNo("TYPE_OF_ACCOUNT");
                                            if (sysCode!=null){
                                                SysCode sys=sysCodeMapper.getCodeNoByNameAndParentNo(sysCode);
                                                if(sys!=null){
                                                    enCommunityVolunteer.setGrid(sys.getCodeNo());
                                                }
                                            }
                                            break;
                                        case 1:
                                            //姓名
                                            enCommunityVolunteer.setName(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //性别
                                            if (cell.getStringCellValue() == "男"||("男").equals(cell.getStringCellValue())) {
                                                enCommunityVolunteer.setSex("1");
                                            } else if (cell.getStringCellValue() == "女"||("女").equals(cell.getStringCellValue())) {
                                                enCommunityVolunteer.setSex("0");
                                            }
                                            break;
                                        case 3:
                                            //年龄
                                            cell.setCellType(CellType.STRING);
                                            enCommunityVolunteer.setAge(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //政治面貌
                                                enCommunityVolunteer.setPoliticalFace(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 5:
                                            //身份证号
                                            enCommunityVolunteer.setIdNum(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 6:
                                            //居住地址
                                            enCommunityVolunteer.setAddress(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 7:
                                            //加入志愿者时间
                                            enCommunityVolunteer.setJoinTime(cell.getDateCellValue()==null?"":cell.getDateCellValue()+"");
                                            break;
                                        case 8:
                                            //创建人
                                            enCommunityVolunteer.setCreateUser(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 9:
                                            //创建时间
                                            cell.setCellType(CellType.STRING);
                                            enCommunityVolunteer.setCreateTime(cell.getStringCellValue()==null?"":cell.getStringCellValue());
                                            break;
                                        case 10:
                                            //位置
                                            cell.setCellType(CellType.STRING);
                                            enCommunityVolunteer.setV1(mapOwnerinfoMapper.selectCoordingbyName(cell.getStringCellValue()));
                                            break;
                                        default:
                                            baseWrapper.setFlag("false");
                                            baseWrapper.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            //将数据放入数据库
                            int count1=enCommunityVolunteerMapper.insertSelective(enCommunityVolunteer);
                            if(count1>0) {
                                count += count1;
                            }
                            dest.delete();
                        }
                    }

                }
            }
            if(count>0){
                baseWrapper.setMsg("ok");
                baseWrapper.setFlag("false");
                return  baseWrapper;
            }
        }catch (Exception e){
            baseWrapper.setMsg("err");
            e.printStackTrace();
        }finally {
            return baseWrapper;
        }
    }

    }
